<!-- FormComponent.vue -->
<template>
	<wd-message-box />
	<wd-toast />
	<wd-form ref="auditForm" labelWidth="120" :model="formData" :rules="formRules">
		<wd-cell-group border>
			<wd-card type="rectangle">
				<template #title>
					<view class="" style="display: flex;">
						<up-avatar :src="globalConfig.appInfo.approvalForm" shape="square"></up-avatar>
						<span style="display: flex;align-items: center;margin-left: 10px;">表单信息</span>
					</view>
				</template>
				<view class="">
					<!-- 动态生成输入项 -->
					<template v-for="item in formFields" :key="item.prop">
						<template v-if="item.visible ? item.visible(formData) : true">
							<!-- input 输入框 -->
							<wd-input v-if="item.type === 'input'" :label="item.label"
								:label-width="item.labelWidth || '150px'" :prop="item.prop"
								v-model="formData[item.prop]" :placeholder="item.placeholder"
								:type="item.inputType || 'text'" :clearable="item.clearable !== false"
								:disabled="item.disabled === true" :show-password="item.ShowPassword === true"
								:readonly="item.readonly === true" />

							<!-- textarea 文本域 -->
							<wd-textarea v-else-if="item.type === 'textarea'" :label="item.label"
								:label-width="item.labelWidth || '150px'" :prop="item.prop"
								v-model="formData[item.prop]" :placeholder="item.placeholder" auto-height
								:clearable="item.clearable !== false" :disabled="item.disabled === true"
								:readonly="item.readonly === true" />

							<!-- InputNumber 计数器 -->
							<wd-cell v-else-if="item.type === 'inputNumber'" :title="item.label"
								:title-width="item.width || '150px'" :prop="item.prop">
								<wd-input-number v-model="formData[item.prop]" :placeholder="item.placeholder"
									allow-null long-press />

							</wd-cell>


							<!-- datetime 时间选择器 -->
							<wd-datetime-picker v-else-if="item.type === 'datetime'"
								:type="item.datetimeType || 'datetime'" :label="item.label" :prop="item.prop"
								v-model="formData[item.prop]" :placeholder="item.placeholder"
								:disabled="item.disabled === true" :default-value="defaulTimetValue"
								@confirm="item.handleConfirm ? item.handleConfirm($event) : null"
								:min-date="item.minDate" :max-date="item.maxDate" />

							<!-- select / selectUser 单复选选择器 -->
							<wd-select-picker v-else-if="['select', 'selectUser'].includes(item.type)"
								:label="item.label" :label-width="item.labelWidth || '150px'" :prop="item.prop"
								v-model="formData[item.prop]"
								:columns="(typeof item.options === 'function' ? item.options() : item.options)"
								:placeholder="item.placeholder" :multiple="item.multiple ?? false"
								:type="item.multiple ? 'checkbox' : 'radio'" :show-confirm="false"
								:value-key="item.valueKey" :label-key="item.labelKey"
								:clearable="item.clearable !== false" :disabled="item.disabled === true" filterable
								@change="item.onChange ? item.onChange($event) : null"
								@confirm="item.onConfirm ? item.onConfirm($event) : null" />


							<!-- radio 复选框 -->
							<wd-cell v-else-if="item.type === 'checkbox'" :title="item.label" :title-width="item.width"
								:prop="item.prop">
								<wd-checkbox-group v-model="formData[item.prop]" :shape="item.shape ?? 'circle'"
									:inline="item.inline" :disabled="item.disabled === true"
									@change="item.onChange ? item.onChange($event) : null">
									<wd-checkbox
										v-for="radio in (typeof item.options === 'function' ? item.options() : item.options)"
										:key="radio[item.optionValue]" :modelValue="radio[item.optionValue]">{{
											radio[item.optionLabel] }}
									</wd-checkbox>
								</wd-checkbox-group>
							</wd-cell>


							<!-- radio 单选框 -->
							<wd-cell v-else-if="item.type === 'radio'" :title="item.label" :title-width="item.width" :prop="item.prop">
								<wd-radio-group v-model="formData[item.prop]" shape="dot" :inline="item.inline"
									:disabled="item.disabled === true" icon-placement="left" max-width="200"
									@change="item.onChange ? item.onChange($event) : null" cell>
									<wd-radio
										v-for="radio in (typeof item.options === 'function' ? item.options() : item.options)"
										:key="radio[item.optionValue]" :value="radio[item.optionValue]">
										{{ radio[item.optionLabel] }}
									</wd-radio>
								</wd-radio-group>
							</wd-cell>

							<!-- upload 文本/图片上传 -->
							<wd-cell v-else-if="item.type === 'upload'" :title="item.label || '文件上传'"
								title-width="100px" :prop="item.prop">
								<wd-upload v-model:file-list="fileLists[item.prop]" :image-mode="item.imageMode"
									:action="item.action" :limit="item.limit" :accept="item.accept"
									:header="item.header" :disabled="item.disabled === true" 
									@success="(response: any) => handleUploadSuccess(item, response)" />
							</wd-cell>

							<!-- rate 评分 -->
							<wd-cell v-else-if="item.type === 'rate'" :title="item.label" title-width="100px" :prop="item.prop">
								<wd-rate v-model="formData[item.prop]" size="20px" space="10px" color="#bababa"
									:disabled="item.disabled === true" :readonly="item.readonly === true" :active-color="[
										'linear-gradient(180deg, rgba(255,238,0,1) 0%,rgba(250,176,21,1) 100%)',
										'linear-gradient(315deg, rgba(245,34,34,1) 0%,rgba(255,117,102,1) 100%)'
									]" @change="item.onChange ? item.onChange($event) : null" />
							</wd-cell>
						</template>
					</template>
				</view>
			</wd-card>
		</wd-cell-group>
		<view class="footer" style="margin-top: 30px;">
			<wd-card type="rectangle" v-if="startUserSelectTasks?.length > 0 &&
				(resubmit == 1 || !detailId)">
				<template #title>
					<view class="" style="display: flex;">
						<up-avatar :src="globalConfig.appInfo.approvalTasks" shape="square"></up-avatar>
						<span style="display: flex;align-items: center;margin-left: 10px;">审批流程</span>
					</view>
				</template>
				<view class="">
					<wd-form ref="startUserSelectAssigneesFormRef" :model="startUserSelectAssignees">
						<wd-cell-group border>
							<wd-select-picker :label="`【${userTask.name}】`" label-width="150px"
								v-for="userTask in startUserSelectTasks" :key="userTask.id" :prop="userTask.id"
								v-model="startUserSelectAssignees[userTask.id]" :columns="userList" value-key="id"
								label-key="nickname" placeholder="请选择审批人" clearable filterable required
								:rules="startUserSelectAssigneesFormRules[userTask.id]"></wd-select-picker>
						</wd-cell-group>
					</wd-form>
				</view>
			</wd-card>
			<view class="" style="display: flex;justify-content: space-evenly;margin: 30px 0 20px 0;">
				<wd-button type="success" @click="submit" custom-class="custom-shadow" block>提交</wd-button>
				<wd-button type="error" @click="cancel" custom-class="custom-shadow" block>取消</wd-button>
			</view>
		</view>
	</wd-form>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted } from 'vue';
import * as UserApi from '@/api/system/user/index'
import { useMessage, useToast } from 'wot-design-uni'




const props = defineProps({
	formFields: {
		type: Array,
		required: true,
	},
	formData: {
		type: Object,
		required: true,
	},
	formRules: {
		type: Object,
		required: true,
	},
	startUserSelectTasks: {
		type: Array,
		required: true,
	},
	startUserSelectAssignees: {
		type: Object,
		required: true,
	},
	startUserSelectAssigneesFormRules: {
		type: Object,
		required: true,
	},
	detailId: {
		type: Number,
		required: true,
	},
	resubmit: {
		type: Number,
		required: true,
	},
	fileLists: {
		type: Object,
		required: false,
	},
});
const message = useMessage()
const toast = useToast()
const emit = defineEmits();
const globalConfig = (getApp() as any).globalData.config;
/**日期选择器默认值 */
const defaulTimetValue = ref<number>(Date.now())
// 获取表单引用
const auditForm = ref<any>(null);
const startUserSelectAssigneesFormRef = ref<any>(null);
const userList = ref<any[]>([])


// 统一的上传成功处理
const handleUploadSuccess = (item: any, response: any) => {
	try {
		console.log('response', response);
		const parsedResponse = JSON.parse(response.file.response)
		const fileUrl = parsedResponse.data // 后端返回的url（字符串）
		// const fileName = response.file.name.split('.').slice(0, -1).join('.')
		const fileName = response.file.name
		// 更新目标字段
		if (item.targetMapping) {
			// 更新 eids 字段
			if (item.targetMapping.fileUrl) {
				const targetKey = item.targetMapping.fileUrl
				if (item.isMultipleArray) {
					if (!Array.isArray(props.formData[targetKey])) {
						props.formData[targetKey] = []
					}
					props.formData[targetKey].push(fileUrl)
				} else {
					// 👉 如果是单文件，直接赋值字符串
					props.formData[targetKey] = fileUrl
				}
			}
			// 更新文件名字段
			if (item.targetMapping.fileName) {
				const targetKey = item.targetMapping.fileName
				if (item.isMultipleArray) {
					if (!Array.isArray(props.formData[targetKey])) {
						props.formData[targetKey] = []
					}
					props.formData[targetKey].push(fileName)
				} else {
					// 👉 如果是单文件，直接赋值字符串
					props.formData[targetKey] = fileName
				}
			}
			// if (item.targetMapping.fileName) {

			// 	const targetKey = item.targetMapping.fileName
			// 	props.formData[targetKey] = fileName
			// }
		}
		toast.success('文件上传成功')
	} catch (error) {
		console.error('文件上传结果解析失败', error)
		toast.error('文件解析失败，请检查格式')
	}
}
/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
/** 提交表单 */
const submit = async () => {
	if (!auditForm.value) {
		throw new Error('表单未初始化')
	}
	// 校验表单
	const { valid, errors } = await auditForm.value.validate();
	if (!valid) {
		console.log('表单校验未通过:', errors);
		return; // ✅ 校验失败，终止后续代码
	}
	// 校验指定审批人
	console.log('props.resubmit', props.resubmit);
	console.log('props.detailId', props.detailId);
	if (props.startUserSelectTasks?.length > 0 &&
		(props.resubmit == 1 || !props.detailId)) {
		console.log('进来了');
		if (!startUserSelectAssigneesFormRef.value) {
			throw new Error('审批人表单未初始化')
		}
		console.log('props.startUserSelectTasks', props.startUserSelectTasks);

		const { valid, errors } = await startUserSelectAssigneesFormRef.value.validate();
		if (!valid) {
			console.log('表单校验未通过:', errors);
			console.log('errors:', errors);
			return; // ✅ 校验失败，终止后续代码
		}
	}
	try {
		const data = props.formData as unknown as any
		// 设置指定审批人
		if (props.startUserSelectTasks?.length > 0) {
			data.startUserSelectAssignees = props.startUserSelectAssignees
		}
		const payload = {
			type: '',
			data
		}
		if (props.detailId) {
			// 编辑模式
			payload.type = 'update'
			emit('submitForm', payload)
		}
		else {
			// 新增模式
			payload.type = 'create'
			emit('submitForm', payload)
		}
	} catch {
		console.log('error');
	}
}
// 取消表单方法
const cancel = () => {
	emit('cancelForm'); // 触发父组件的取消事件
};
onMounted(() => {
	console.log('formFields', props.formFields);
	getUserList()
})
</script>

<style scoped>
/* 你可以在这里添加样式 */
</style>